//
//  AddressBookGroup.m
//  TestAB
//
//  Created by Hunk on 12-2-24.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "AddressBookGroup.h"
#import "AddressBookPerson.h"

@implementation AddressBookGroup
@synthesize record    = _record;
@synthesize hasMember = _hasMember;

- (id)initWithRecord:(ABRecordRef)record
{
    if((self = [super init]))
    {
        _record = record;
    }
    return self;
}

#pragma mark -
#pragma mark record
- (ABRecordRef)record
{
    return _record;
}

#pragma mark -
#pragma mark hasMember
- (BOOL)hasMember
{
    return (0 == [self groupMembersCount]) ? NO : YES;
}

#pragma mark -
#pragma mark Get group name
- (NSString *)groupName
{
    if(_record)
    {
        return (NSString *)ABRecordCopyValue(_record, kABGroupNameProperty);
    }
    
    return nil;
}

- (NSInteger)groupMembersCount
{
    if(_record)
    {
        CFArrayRef arrayRef = ABGroupCopyArrayOfAllMembers(_record);
        
        if(arrayRef)
        {
            NSInteger nCount = CFArrayGetCount(arrayRef);
            SAFE_CFRELEASE(arrayRef)
        
            return nCount;
        }
    }
    return 0;
}

#pragma mark -
#pragma mark Get group name
- (NSArray *)groupMembers
{    
//    NSArray* groupMembersArray = (NSArray*)ABGroupCopyArrayOfAllMembers(_record);
    NSArray* groupMembersArray = (NSArray*)ABGroupCopyArrayOfAllMembersWithSortOrdering(_record, kABPersonSortByLastName);

    NSMutableArray* abGroupsArray = [[NSMutableArray alloc] init];
    
    for(int i = 0; i < [groupMembersArray count]; i++)
    {
        ABRecordRef peopleRecord = (ABRecordRef)[groupMembersArray objectAtIndex:i];
        
        // Set AddressBookPerson
        AddressBookPerson* addressBookPerson = [[AddressBookPerson alloc] initWithRecord:peopleRecord];
        
        [abGroupsArray addObject:addressBookPerson];
        
        [addressBookPerson release];
    }
    
    return [abGroupsArray autorelease];
}

- (void)dealloc
{   
    SAFE_CFRELEASE(_record)
    
    [super dealloc];
}

@end
